package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketAdExample;
import com.cskaoyan.market.db.mapper.MarketAdMapper;
import com.cskaoyan.market.service.MarketAdService;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class MarketAdServiceImpl implements MarketAdService {

    @Override
    public List<MarketAd> list(String page, String limit, String name, String content, String sort, String order) {
        SqlSession session = MyBatisUtil.getSession();
        MarketAdMapper adMapper = session.getMapper(MarketAdMapper.class);
        //创建查询条件
        MarketAdExample marketAdExample = new MarketAdExample();
        marketAdExample.or().andNameLike("%" + name + "%").
                andContentLike("%" + content + "%").andDeletedEqualTo(false);
        marketAdExample.orderBy(sort + " " + order);
        //分页插件分页
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketAd> marketAds = adMapper.selectByExample(marketAdExample);
        session.commit();
        session.close();
        return marketAds;
    }

    @Override
    public MarketAd update(MarketAd ad) {
        SqlSession session = MyBatisUtil.getSession();
        MarketAdMapper mapper = session.getMapper(MarketAdMapper.class);
        //根据Id修改广告
        mapper.updateByPrimaryKeySelective(ad);
        session.commit();
        session.close();
        return ad;
    }

    @Override
    public void deleteAd(String id) {
        SqlSession session = MyBatisUtil.getSession();
        MarketAdMapper mapper = session.getMapper(MarketAdMapper.class);
        //设置好广告对应Id和逻辑删除的条件
        MarketAd record = new MarketAd();
        record.setId(Integer.parseInt(id));
        record.setDeleted(true);
        mapper.updateByPrimaryKeySelective(record);
        session.commit();
        session.close();
    }

    @Override
    public MarketAd createAd(MarketAd marketAd) {
        SqlSession session = MyBatisUtil.getSession();
        MarketAdMapper mapper = session.getMapper(MarketAdMapper.class);
        mapper.insertSelective(marketAd);
        session.commit();
        session.close();
        return marketAd;
    }

}
